﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using XCI.Data.Entity;

namespace XCI.Data
{
    /// <summary>
    /// 活动记录
    /// </summary>
    public class ActiveRecord
    {
        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <returns>返回新创建的数据库对象</returns>
        public virtual Database GetDatabase()
        {
            return new Database();
        }
    }

    /// <summary>
    /// 活动记录扩展操作
    /// </summary>
    public static class ActiveRecordExtensions
    {
        /// <summary>
        /// 保存数据(根据主键)
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public static int Save<T>(this ActiveRecord entity)
        {
            var meta = EntityHelper.Get<T>();
            var pkValue = meta.PrimaryProperty.GetValue(entity);
            using (var db = entity.GetDatabase())
            {
                if (pkValue == null)
                {
                    return db.Insert(entity);
                }
                else
                {
                    return db.Update(entity);
                }
            }
        }
    }
}
